import React, { useState, useEffect } from 'react'
import { 
  getPerformanceStats, 
  subscribeToPerformanceUpdates, 
  unsubscribeFromPerformanceUpdates 
} from '../services/sharePregeneration'

const PerformanceMonitor = ({ isVisible = false, onToggle }) => {
  const [stats, setStats] = useState({
    totalRequests: 0,
    cacheHits: 0,
    cacheMisses: 0,
    hitRate: 0,
    avgGenerationTime: 0,
    avgRetrievalTime: 0,
    currentCacheSize: 0,
    recentActivity: []
  })
  const [isExpanded, setIsExpanded] = useState(false)

  useEffect(() => {
    if (isVisible) {
      // 订阅性能数据更新
      const updateStats = () => {
        const newStats = getPerformanceStats()
        setStats(newStats)
      }

      // 初始加载
      updateStats()

      // 订阅实时更新
      subscribeToPerformanceUpdates(updateStats)

      // 每秒更新一次
      const interval = setInterval(updateStats, 1000)

      return () => {
        clearInterval(interval)
        unsubscribeFromPerformanceUpdates(updateStats)
      }
    }
  }, [isVisible])

  if (!isVisible) {
    return (
      <button
        onClick={onToggle}
        className="fixed bottom-4 right-4 z-50 bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white p-3 rounded-full shadow-lg transition-all duration-200 hover:scale-110"
        title="打开性能监控"
      >
        📊
      </button>
    )
  }

  const formatTime = (ms) => {
    if (ms < 1000) return `${ms.toFixed(0)}ms`
    return `${(ms / 1000).toFixed(1)}s`
  }

  const getHitRateColor = (rate) => {
    if (rate >= 80) return 'text-green-600'
    if (rate >= 60) return 'text-yellow-600'
    return 'text-red-600'
  }

  const getActivityIcon = (type) => {
    switch (type) {
      case 'pregeneration': return '🎨'
      case 'cache_hit': return '⚡'
      case 'cache_miss': return '🔄'
      default: return '📄'
    }
  }

  return (
    <div className="fixed bottom-4 right-4 z-50 bg-white/95 backdrop-blur-md border border-gray-200 rounded-2xl shadow-xl max-w-sm w-80">
      {/* 标题栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-100">
        <div className="flex items-center space-x-2">
          <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse"></div>
          <h3 className="text-sm font-semibold text-gray-800">性能监控</h3>
        </div>
        <div className="flex items-center space-x-2">
          <button
            onClick={() => setIsExpanded(!isExpanded)}
            className="text-gray-500 hover:text-gray-700 transition-colors duration-200"
            title={isExpanded ? "折叠" : "展开"}
          >
            {isExpanded ? '📖' : '📋'}
          </button>
          <button
            onClick={onToggle}
            className="text-gray-500 hover:text-gray-700 transition-colors duration-200"
            title="关闭监控"
          >
            ✕
          </button>
        </div>
      </div>

      {/* 基础统计 */}
      <div className="p-4 space-y-3">
        {/* 缓存命中率 */}
        <div className="flex items-center justify-between">
          <span className="text-sm text-gray-600">缓存命中率</span>
          <span className={`text-lg font-bold ${getHitRateColor(stats.hitRate)}`}>
            {stats.hitRate.toFixed(1)}%
          </span>
        </div>

        {/* 命中/未命中统计 */}
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <span className="text-gray-600">命中: {stats.cacheHits}</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-2 h-2 bg-orange-500 rounded-full"></div>
              <span className="text-gray-600">未命中: {stats.cacheMisses}</span>
            </div>
          </div>
        </div>

        {/* 响应时间 */}
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">平均生成时间</span>
            <span className="font-mono text-blue-600">
              {formatTime(stats.avgGenerationTime)}
            </span>
          </div>
          <div className="flex items-center justify-between text-sm">
            <span className="text-gray-600">平均获取时间</span>
            <span className="font-mono text-green-600">
              {formatTime(stats.avgRetrievalTime)}
            </span>
          </div>
        </div>

        {/* 缓存状态 */}
        <div className="flex items-center justify-between text-sm">
          <span className="text-gray-600">当前缓存</span>
          <span className="font-semibold text-purple-600">
            {stats.currentCacheSize} 项
          </span>
        </div>
      </div>

      {/* 详细信息 */}
      {isExpanded && (
        <div className="border-t border-gray-100">
          <div className="p-4">
            <h4 className="text-sm font-semibold text-gray-700 mb-3">
              最近活动 <span className="text-xs text-gray-500">(最新10条)</span>
            </h4>
            <div className="space-y-2 max-h-32 overflow-y-auto">
              {stats.recentActivity.length === 0 ? (
                <div className="text-xs text-gray-400 text-center py-2">
                  暂无活动记录
                </div>
              ) : (
                stats.recentActivity.slice(0, 10).map((activity, index) => (
                  <div 
                    key={index}
                    className="flex items-center justify-between text-xs bg-gray-50 rounded-lg p-2"
                  >
                    <div className="flex items-center space-x-2">
                      <span>{getActivityIcon(activity.type)}</span>
                      <span className="text-gray-700">{activity.description}</span>
                    </div>
                    <div className="text-gray-500 font-mono">
                      {formatTime(activity.duration)}
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* 性能提升显示 */}
          {stats.hitRate > 0 && (
            <div className="p-4 border-t border-gray-100 bg-gradient-to-r from-green-50 to-blue-50">
              <div className="flex items-center space-x-2">
                <span className="text-2xl">🚀</span>
                <div>
                  <div className="text-sm font-semibold text-gray-800">
                    性能提升效果
                  </div>
                  <div className="text-xs text-gray-600">
                    缓存命中节省 {formatTime(stats.avgGenerationTime - stats.avgRetrievalTime)} 时间
                  </div>
                  {stats.hitRate >= 80 && (
                    <div className="text-xs text-green-600 font-semibold mt-1">
                      ✨ 优化效果显著！
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  )
}

export default PerformanceMonitor